<template>
  <div class="app-container">
    <!-- 条件查询区域开始 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-row>
          <!-- 地区名称 -->
          <el-col :span="6">
            <el-form-item
              :label="$t('dictRegion.regionName')"
              prop="likeRegionName"
            >
              <el-input
                v-model="queryParams.likeRegionName"
                :placeholder="$t('dictRegion.regionNamePlaceholder')"
                @keyup.enter="tableHooks.handleQuery()"
                class="!w-[203px]"
              />
            </el-form-item>
          </el-col>
          <!-- 是否启用 -->
          <el-col :span="6">
            <el-form-item :label="$t('dictRegion.enable')" prop="enable">
              <jmash-select
                v-model="queryParams.enable"
                :placeholder="$t('dictRegion.enablePlaceholder')"
                :data="Dict.enableDict.values"
                clearable
                class="!w-[203px]"
                @change="tableHooks.handleQuery()"
              />
            </el-form-item>
          </el-col>
          <!-- 查询重置 -->
          <el-col :span="6" style="margin-left: auto">
            <el-form-item class="search-btn">
              <el-button type="primary" @click="tableHooks.handleQuery()">
                {{ $t("common.search") }}
              </el-button>
              <el-button @click="tableHooks.resetQuery()">
                {{ $t("common.reset") }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="clear"></div>
      <!-- 条件查询区域结束 -->
    </div>
    <el-card shadow="never" class="table-container">
      <!-- 按钮开始 -->
      <template #header>
        <el-row>
          <el-col :span="17">
            <!-- 新增 -->
            <el-button
              type="primary"
              v-hasPerm="['region:dict_region:add']"
              @click="handleAdd()"
            >
              {{ $t("common.add") }}
            </el-button>
          </el-col>
          <el-col :span="7" class="container-float">
            <!-- 导入 -->
            <el-button
              plain
              type="primary"
              v-hasPerm="['region:dict_region:import']"
              @click="uploadVisible = true"
            >
              {{ $t("common.import") }}
            </el-button>
            <!-- 导出 -->
            <el-button
              plain
              type="primary"
              v-hasPerm="['region:dict_region:export']"
              @click="tableHooks.handleExport(t('dictRegion.name'))"
            >
              {{ $t("common.export") }}
            </el-button>
            <jmash-column-select
              v-model="tableLabel"
              label-name="region/os-dict-region"
            />
          </el-col>
        </el-row>
      </template>
      <!-- 按钮结束 -->
      <!-- 表格开始 -->
      <jmash-table
        ref="multipleTableRef"
        row-key="regionId"
        lazy
        :list-loading="listLoading"
        :data="tableData"
        :table-label="tableLabel"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :is-selection="false"
        :load="handleLoad"
        @sort-change="handleSort"
      >
        <!-- 地区类型 -->
        <template #regionType="scope">
          <span>
            {{ Dict.regionTypeEnum.getEnumValue(scope.data.row.regionType) }}
          </span>
        </template>
        <!-- 省分类 -->
        <template #regionCategory="scope">
          <span>
            {{
              Dict.regionCategoryEnum.getEnumValue(
                scope.data.row.regionCategory,
              )
            }}
          </span>
        </template>
        <!-- 是否启用 -->
        <template #enable="scope">
          <el-switch
            v-model="scope.data.row.enable"
            @change="
              tableHooks.enableRecord(scope.data.row, scope.data.row.enable)
            "
          />
        </template>
        <!-- 排序 -->
        <template #orderBy="scope">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="下移"
            placement="top"
          >
            <el-icon
              style="cursor: pointer"
              size="16"
              @click="handleMove(scope.data.row, false)"
            >
              <Bottom />
            </el-icon>
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="上移"
            placement="top"
          >
            <el-icon
              style="cursor: pointer"
              size="16"
              @click="handleMove(scope.data.row, true)"
            >
              <Top />
            </el-icon>
          </el-tooltip>
        </template>
        <!-- 操作 -->
        <template #operation="scope">
          <span
            class="el-button-color"
            v-hasPerm="['region:dict_region:add']"
            @click="handleAdd(scope.data.row.regionId)"
          >
            {{ $t("dictRegion.addChild") }}
          </span>
          <span
            class="el-button-color dropdown-left"
            v-hasPerm="['region:dict_region:update']"
            @click="handleEdit(scope.data.row)"
          >
            {{ $t("common.edit") }}
          </span>
          <span
            class="el-button-color dropdown-left"
            v-hasPerm="['region:dict_region:delete']"
            @click="handleDelete(scope.data.row)"
          >
            {{ $t("common.delete") }}
          </span>
        </template>
      </jmash-table>
      <!-- 分页 -->
      <template #footer>
        <jmash-pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:current-page="queryParams.curPage"
          v-model:page-size="queryParams.pageSize"
          @pagination="tableHooks.getList()"
        />
      </template>
    </el-card>

    <!-- 新增编辑 -->
    <Edit
      v-if="editDialog.visible"
      v-model="editDialog.visible"
      :title="editDialog.title"
      :entity-key="entityKey"
      :parent-id="parentId"
      @refresh="refresh"
      @reload="handleReload"
      width="900px"
    />

    <!-- 上传 -->
    <jmash-import-upload
      v-if="uploadVisible"
      :upload-visible="uploadVisible"
      :template-title="$t('sysUser.templateDownload')"
      @template-down="tableHooks.downloadTemplate(t('dictRegion.name'))"
      @import-events="importExcel"
      @upload-closed="uploadClosed"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import {
  useTableHooks,
  type DialogRef,
  type TableColumn,
  type TableSort,
} from "jmash-core";

import { dictRegionApi } from "@/api/region/os-dict-region";
import type {
  DictRegionImportReq,
  DictRegionKey,
  DictRegionModel,
  DictRegionReq,
} from "@/api/region/os-dict-region/types";

import { Dict } from "@/api/region";

import Edit from "./edit.vue";

import { useI18n } from "vue-i18n";
import { Constant } from "@/constant";
import { ElMessage, ElMessageBox } from "element-plus";
const { t } = useI18n();

const queryParams = ref<DictRegionReq>({
  likeRegionName: undefined,
  enable: undefined,
  parentId: undefined,
});

const tableLabel = ref<TableColumn[]>([
  {
    label: "dictRegion.regionName",
    prop: "regionName",
    isColumn: true,
    minWidth: "300",
  },
  {
    label: "dictRegion.regionCode",
    prop: "regionCode",
    width: "100",
    isColumn: true,
  },
  {
    label: "dictRegion.regionType",
    prop: "regionType",
    slotName: "regionType",
    columnType: "slot",
    width: "100",
    isColumn: true,
  },
  {
    label: "dictRegion.regionCategory",
    prop: "regionCategory",
    slotName: "regionCategory",
    columnType: "slot",
    width: "100",
    isColumn: true,
  },
  {
    label: "dictRegion.enable",
    prop: "enable",
    slotName: "enable",
    width: "100",
    columnType: "slot",
    isColumn: true,
  },
  {
    label: "dictRegion.orderBy",
    prop: "orderBy",
    slotName: "orderBy",
    columnType: "slot",
    width: "70",
    isColumn: true,
  },
  {
    label: "common.operate",
    width: "200",
    slotName: "operation",
    columnType: "slot",
    fixed: "right",
    isColumn: true,
  },
]);

const {
  tableHooks,
  multipleTableRef,
  queryFormRef,
  listLoading,
  tableData,
  total,
} = useTableHooks(t, dictRegionApi, queryParams);

//编辑Dialog
const editDialog = ref<DialogRef>({
  title: t("common.edit"),
  visible: false,
});
const entityKey = ref<DictRegionKey>({});
// 新增默认选中父级
const parentId = ref<string | undefined>("");
// 新增
const handleAdd = (regionId?: string) => {
  entityKey.value = {};
  parentId.value = regionId;
  editDialog.value.title = t("common.add");
  editDialog.value.visible = true;
};
// 修改
const handleEdit = (row: DictRegionModel) => {
  parentId.value = "";
  entityKey.value = row;
  editDialog.value.title = t("common.edit");
  editDialog.value.visible = true;
};

// 上传
const uploadVisible = ref(false);
// 导入Excel.
const importExcel = (val: DictRegionImportReq) => {
  val.updateMask = "";
  tableHooks.importExcel(val).then((response) => {
    uploadVisible.value = false;
  });
};
// 关闭导入弹框
const uploadClosed = () => {
  uploadVisible.value = false;
};

// 处理排序
const handleSort = (sort: TableSort) => {
  tableHooks.handleSort(sort.prop, sort.order);
};

// 查询数据
tableHooks.getList();

// 存储懒加载的树形数据
const lazyData = new Map();
// 表格懒加载
const handleLoad = (
  row: DictRegionModel,
  treeNode: unknown,
  resolve: (data: DictRegionModel[]) => void,
) => {
  lazyData.set(row.regionId, { row, treeNode, resolve });
  dictRegionApi
    .findList({ ...queryParams.value, parentId: row.regionId })
    .then(({ data }) => {
      resolve(data.results);
      if (!data.results.length) {
        const { store } = multipleTableRef.value.refs();
        store.states.lazyTreeNodeMap.value[row.regionId] = [];
      }
    });
};

/**
 * 从子组件传过来的事件，刷新列表
 * @returns {void}
 */
const refresh = (value: boolean) => {
  if (!value) return;
  tableHooks.getList();
};

// 排序
const handleMove = (row: DictRegionModel, up: boolean) => {
  dictRegionApi.move({ regionId: row.regionId }, up).then((res) => {
    if (res.status === 200) {
      !handleReloadChildren(row.parentId as string) && tableHooks.getList();
    }
  });
};

// 删除
const handleDelete = (row: DictRegionModel) => {
  ElMessageBox.confirm(t("common.confirmDelete"), t("common.delete"), {
    cancelButtonText: t("common.cancel"),
    confirmButtonText: t("common.confirm"),
    type: "warning",
  })
    .then(() => dictRegionApi.delete({ regionId: row.regionId }))
    .then((res) => {
      if (res.status === 200) {
        ElMessage({
          message: t("common.deleteSuccess"),
          type: "success",
        });
        !handleReloadChildren(row.parentId as string) &&
          tableHooks.handleQuery();
      }
    });
};

// 新增修改组件传递事件触发渲染
const handleReload = (row: DictRegionModel) => {
  if (!row.parentId || row.parentId === Constant.DEFAULT_ID) {
    tableHooks.getList();
    return;
  }
  handleReloadChildren(row.parentId as string);
};

// 重新渲染子级
const handleReloadChildren = (id: string): boolean => {
  if (!lazyData.has(id) || !id) return false;
  const { row, treeNode, resolve } = lazyData.get(id);
  handleLoad(row, treeNode, resolve);
  return true;
};
</script>
